$(function() {
    var _href = window.location.href;
    if (_href.indexOf('/study/index') != -1) {
        $('#open-history-list').removeClass('history-lecture-list');
    }
    //初始进入 全部数据
    changeTabs('courseAll');

    $('body').on('click', '#tabs>a', function () {
        var _this = $(this);
        if (_this.hasClass('active')) return;
        _this.siblings().removeClass("active");
        _this.addClass("active");
        var _id = _this.attr('id');
        console.log(_id);
        changeTabs(_id);
    }).on('click', '.bespeak-btn', function () {
        var openId = $(this).data('id');
        bespeak(openId);
    })

    $('.lecture-date-num').on('click', 'li', function () {
        var that = $(this),
            currDate = that.data('date');
        if(that.hasClass('active')) return;
        that.addClass('active').siblings().removeClass('active');
        var date = new Date(currDate);
        loadDateClassCourse(date);

    })

});

function changeTabs(obj) {
    $("#course-list").find("li").remove();
    var date = new Date();
    var pickerSelected = $(".picker-calendar-day-selected");
    var cTypeKey = $("#courseTypeKey");
    //切换tab时获取选中的时间
    if (pickerSelected.data('date')) {
        date = new Date(pickerSelected.data('date'));
        date.setMonth(date.getMonth() + 1);
    } else {
        var currentTime = $(".lecture-date-num>li");
        $.each(currentTime, function () {
            var that = $(this)
            if (that.hasClass('active')) {
                date = new Date(that.data('date'));
            }
        });
    }
    switch(obj) {
        case 'courseAll':
            cTypeKey.val('');  //全部
            break;
        case 'courseLive':
            cTypeKey.val('LIVE');  //直播
            break;
        case 'courseSmall':
            cTypeKey.val('SMALL'); //小班课
            break;
        case 'courseOpen':
            cTypeKey.val('OPEN'); //公开课
            break;
    }

    loadDateClassCourse(date);
}

/**
 * 预约免费直播
 * @param openId 免费直播ID
 */
function bespeak(openId) {
    isLogin(function () {
        $.ajax({
            url: baseloaction + '/mobile/uc/open/bespeakOpen',
            type: 'post',
            dataType: 'json',
            data: {
                'openId': openId
            },
            success: function (result) {
                $('span[data-id="' + openId + '"]').text('已预约').removeClass('bespeak-btn');
                $.toast(result.message);
            },
            error: function (error) {
                $.toast('系统错误，免费直播预约失败');
            }
        });
    });
}

function loadDateClassCourse(date) {
    var loading = '<section class="loading-gif__wrap"><div class="row"><aside class="col-auto"><span class="loadingImg"></span></aside><aside class="col-auto"><span class="loading-txt"><big>努力奔跑中...</big><br>';
    // if (copyRight != "off"){
    //     loading +=  '<small>Powered by 268教育软件';
    // }
    loading += '</small></span></aside></div></section>';
    $("#course-list").html(loading);
    setTimeout(function () {
        loadClssCourse(date);
    }, 1000);
}

// 加载免费直播
function loadClssCourse(date) {

    var params = {
        "year": date.getFullYear(),
        "month": date.getMonth() + 1,
        "date": date.getDate(),
        "courseTypeKey": $("#courseTypeKey").val()
    };
    params = JSON.stringify(params);
    $.ajax({
        url: baseloaction + '/mobile/uc/ajax/load/classSchedule',
        data: params,
        type: 'post',
        dataType: 'text',
        async: false,
        contentType:'application/json;charset=utf-8',
        success: function (result) {
            $("#course-list").html(result)
        }
    });
}

function onEnterLiveRoom(openId) {
    isLogin(function () {
        $.ajax({
            url: baseloaction + '/mobile/open/ajax/play',
            data: {'openId': openId},
            success: function (result) {
                if (result.success == true) {
                    var noMobile = getCookie("noMobile");
                    if (noMobile != null) {
                        if(result.status != "REPLAY"){
                            if (noMobile == "2") {
                                if("CC" == result.entity.playType) {
                                    window.webkit.messageHandlers.enterLiveRoom.postMessage(JSON.stringify({playType:result.entity.playType,
                                        roomId:result.entity.roomId,
                                        studentCode:result.entity.studentCode,
                                        liveAccount:result.entity.liveAccount,
                                        courseId:"0",catalogId:"0",materialId:"0"}));
                                }else{
                                    window.webkit.messageHandlers.enterLiveRoom.postMessage(JSON.stringify({playType:result.entity.playType,
                                        roomId:result.entity.tLiveParams.roomId,userId:result.entity.tLiveParams.userId,
                                        safeKey:result.entity.tLiveParams.safeKey,timeStamp:result.entity.tLiveParams.timeStamp,
                                        expires:result.entity.tLiveParams.expires,
                                        courseId:"0"}));
                                }
                            } else {
                                if("CC" == result.entity.playType){
                                    android.enterLiveRoom(result.entity.playType,
                                        result.entity.roomId,
                                        result.entity.studentCode,
                                        result.entity.liveAccount,
                                        "0", "0", "0","0","0");
                                }else{
                                    android.enterLiveRoom(result.entity.playType,result.entity.tLiveParams.roomId,
                                        result.entity.tLiveParams.userId,
                                        result.entity.tLiveParams.safeKey,
                                        result.entity.tLiveParams.timeStamp,
                                        result.entity.tLiveParams.expires, "0", "0","0");
                                }
                            }
                            return true;
                        }else{
                            if (typeof result.entity.backCode == 'undefined' || result.entity.backCode.indexOf("http")) {
                                if (noMobile == "2") {
                                    window.webkit.messageHandlers.replayiOS.postMessage(JSON.stringify({replayType:"VIDEO",
                                        playName:result.entity.catalogName,
                                        playCode:result.entity.backCode,
                                        playUrl:result.entity.backCode,
                                        courseId:"",
                                        catalogId:"",
                                        materialId:"",
                                        userId:"",
                                        roomId:"",
                                        liveId:"",
                                        recordId:"",
                                        studentCode:"",
                                        duration:result.entity.duration
                                    }));
                                } else {
                                    android.replay('VIDEO', result.entity.courseName, result.entity.backCode,result.entity.backCode, "", "", "","","","","","","0");
                                }
                            }else {
                                var index=result.entity.backCode.indexOf("?");
                                var paramUrl=result.entity.backCode.substring(index + 1);
                                var param=paramUrl.split("&");
                                var liveId = "";
                                var recordId = "";
                                var userId=''
                                $.each(param,function (index,value) {
                                    var temp= value.split("=")
                                    if (temp[0]=='liveid') {
                                        liveId=temp[1];
                                    }else if (temp[0]=='recordid'){
                                        recordId=temp[1]
                                    }else if (temp[0] == 'userid') {
                                        userId=temp[1]
                                    }
                                })
                                if (noMobile == "2") {
                                    window.webkit.messageHandlers.replayiOS.postMessage(JSON.stringify({
                                        replayType:"LIVE",
                                        playName:result.entity.catalogName,
                                        playCode:result.entity.backCode,
                                        playUrl:result.entity.backCode,
                                        courseId:"",
                                        catalogId:"",
                                        materialId:"",
                                        userId:userId,
                                        roomId:result.entity.roomId,
                                        liveId:liveId,
                                        recordId:recordId,
                                        studentCode:result.entity.studentCode,
                                        duration:result.entity.duration
                                    }));
                                } else {
                                    android.replay('LIVE', result.entity.courseName, result.entity.backCode, result.entity.backCode, "", "", "",userId,result.entity.roomId,liveId,recordId,result.entity.studentCode,"0");
                                }
                            }
                        }
                    }
                } else {
                    $.toast(result.message);
                }
            },
            error: function () {
                $.toast('系统繁忙，请稍候再试');
            }
        });
    });
}


function enterLive(packageId,courseId, courseType, materialId, catalogId, livePlayState, replay, catalogName, backCode) {
    if (packageId == 'null' || packageId == '') {
        packageId = courseId;
    }
    var noMobile = getCookie("noMobile");
    if (noMobile != null) {
        if (noMobile == "1" || noMobile == "2") {
            $.ajax({
                url: baseloaction + '/mobile/uc/play/checkPlay',
                data: {
                    catalogId: catalogId,
                    buyCourseId:packageId,
                    userId: $("#userId").val(),
                    prevCatalogId:0,
                    courseId:courseId,
                },
                success: function (res) {
                    if (res.success ==false) {
                        $.toast(res.message);
                    }else{
                        //loadPlayData(res.entity.sign);
                        $.ajax({
                            url:baseloaction+"/mobile/uc/ajax/findMaterialId",
                            data: {
                                materialId: materialId,
                                catalogId: catalogId,
                                courseId:courseId,
                                livePlayState:livePlayState
                            },
                            dataType:"json",
                            type:"post",
                            success:function (result) {
                                if (courseType == 'SMALL') {//如果是小班课
                                    if (livePlayState == 1 || livePlayState == 4) {
                                        if (noMobile == "2") {
                                            if ("CC" == result.playType) {
                                                window.webkit.messageHandlers.enterClassLiveRoom.postMessage(JSON.stringify({playType:result.playType,
                                                    roomUrl:result.studentUrl,studentCode:result.studentCode,
                                                    courseId:courseId, catalogId:catalogId,materialId:materialId}));
                                            }else{
                                                window.webkit.messageHandlers.enterClassLiveRoom.postMessage(JSON.stringify({playType:result.playType,
                                                    roomId:result.tLiveParams.roomId,userId:result.tLiveParams.userId,
                                                    safeKey:result.tLiveParams.safeKey,timeStamp:result.tLiveParams.timeStamp,
                                                    expires:result.tLiveParams.expires, courseId:courseId, catalogId:catalogId,materialId:materialId}));
                                            }
                                        } else {
                                            if ("CC" == result.playType) {
                                                android.enterClassLiveRoom(result.playType, result.studentUrl, result.studentCode, "","","",courseId, catalogId, materialId);
                                            }else{
                                                android.enterClassLiveRoom(result.playType, result.tLiveParams.roomId,
                                                    result.tLiveParams.userId,
                                                    result.tLiveParams.safeKey,
                                                    result.tLiveParams.timeStamp,
                                                    result.tLiveParams.expires,
                                                    courseId, catalogId, materialId);
                                            }
                                        }
                                    } else if (livePlayState == 3 && replay == 1) {
                                        if (typeof backCode == 'undefined' || backCode.indexOf("http")) {
                                            if (noMobile == "2") {
                                                window.webkit.messageHandlers.replayiOS.postMessage(JSON.stringify({replayType:"VIDEO", playName:catalogName, playCode:backCode, playUrl:backCode,courseId:courseId,catalogId:catalogId,materialId:materialId,duration:result.duration}));
                                            } else {
                                                android.replay('VIDEO', catalogName, backCode, backCode, courseId, catalogId, materialId,result.duration);
                                            }
                                        } else {
                                            var backCodeUrl=backCode+"&autoLogin=true&viewertoken="+result.studentCode+"&viewername=null"
                                            if (noMobile == "2") {
                                                window.webkit.messageHandlers.replayiOS.postMessage(JSON.stringify({replayType:"LIVE", playName:catalogName, playCode:backCodeUrl, playUrl:backCodeUrl,courseId:courseId,catalogId:catalogId,materialId:materialId,duration:result.duration}));
                                            } else {
                                                android.replay('LIVE', catalogName, backCode, backCode, courseId, catalogId, materialId,result.duration);
                                            }
                                        }
                                    }
                                } else {//如果是直播
                                    if (livePlayState == 1 || livePlayState == 4) {
                                        if (noMobile == "2") {
                                            if ("CC" == result.playType) {
                                                window.webkit.messageHandlers.enterLiveRoom.postMessage(JSON.stringify(
                                                    {playType:result.playType,roomId:result.roomId,studentCode:result.studentCode,
                                                        liveAccount:result.liveAccount,courseId:courseId,
                                                        catalogId:catalogId,materialId:materialId}));
                                            }else{
                                                window.webkit.messageHandlers.enterLiveRoom.postMessage(JSON.stringify(
                                                    {playType:result.playType,roomId:result.tLiveParams.roomId,userId:result.tLiveParams.userId,
                                                        safeKey:result.tLiveParams.safeKey,timeStamp:result.tLiveParams.timeStamp,
                                                        expires:result.tLiveParams.expires,courseId:courseId,
                                                        catalogId:catalogId,materialId:materialId}));
                                            }
                                        } else {
                                            if ("CC" == result.playType) {
                                                android.enterLiveRoom(result.playType,
                                                    result.roomId, result.studentCode,
                                                    result.liveAccount, "", "",
                                                    courseId, catalogId, materialId);
                                            } else {
                                                android.enterLiveRoom(result.playType, result.tLiveParams.roomId,
                                                    result.tLiveParams.userId,
                                                    result.tLiveParams.safeKey,
                                                    result.tLiveParams.timeStamp,
                                                    result.tLiveParams.expires,
                                                    courseId, catalogId, materialId);
                                            }
                                        }
                                    } else if (livePlayState == 3 && replay == 1) {
                                        if (typeof backCode == 'undefined' || backCode.indexOf("http")) {
                                            if (noMobile == "2") {
                                                window.webkit.messageHandlers.replayiOS.postMessage(JSON.stringify({replayType:"VIDEO",
                                                    playName:catalogName,
                                                    playCode:backCode,
                                                    playUrl:backCode,
                                                    courseId:courseId,
                                                    catalogId:catalogId,
                                                    materialId:materialId,
                                                    userId:"",
                                                    roomId:"",
                                                    liveId:"",
                                                    recordId:"",
                                                    studentCode:"",
                                                    duration:result.duration
                                                }));
                                            } else {
                                                android.replay('VIDEO', catalogName, backCode, backCode, courseId, catalogId, materialId,"","","","","",result.duration);
                                            }
                                        }else {
                                            var index=backCode.indexOf("?");
                                            var paramUrl=backCode.substring(index + 1);
                                            var param=paramUrl.split("&");
                                            var liveId = "";
                                            var recordId = "";
                                            var userId=''
                                            $.each(param,function (index,value) {
                                                var temp= value.split("=")
                                                if (temp[0]=='liveid') {
                                                    liveId=temp[1];
                                                }else if (temp[0]=='recordid'){
                                                    recordId=temp[1]
                                                }else if (temp[0] == 'userid') {
                                                    userId=temp[1]
                                                }
                                            })
                                            if (noMobile == "2") {
                                                window.webkit.messageHandlers.replayiOS.postMessage(JSON.stringify({
                                                        replayType:"LIVE",
                                                        playName:catalogName,
                                                        playCode:backCode,
                                                        playUrl:backCode,
                                                        courseId:courseId,
                                                        catalogId:catalogId,
                                                        materialId:materialId,
                                                        userId:userId,
                                                        roomId:result.roomId,
                                                        liveId:liveId,
                                                        recordId:recordId,
                                                        studentCode:result.studentCode,
                                                        duration:result.duration
                                                    }));
                                            } else {
                                                android.replay('LIVE', catalogName, backCode, backCode, courseId, catalogId, materialId,userId,result.roomId,liveId,recordId,result.studentCode,result.duration);
                                            }
                                        }
                                    }
                                }
                            }
                        })
                    }
                }
            })
        }
        return true;
    }

    if (courseType == 'LIVE') {
        window.location.href = baseloaction + '/mobile/course/liveInfo?courseId=' + courseId + '&catalogId=' + catalogId;
    } else {
        window.location.href = baseloaction + '/mobile/course/smallClassInfo?courseId=' + courseId + '&catalogId=' + catalogId;
    }
}

function loadPlayData(sign) {
    $.ajax({
        url: baseloaction + "/mobile/uc/play/loadPlayData",
        data:{'sign':sign},
        dataType:"json",
        type:"post",
        success:function (res) {

        }
    })
}
function goBack() {
    var noMobile = getCookie("noMobile");
    if (noMobile != null) {
        if (noMobile == "1" ){
            android.goBack();
        }
        if( noMobile == "2") {
            window.webkit.messageHandlers.goBack.postMessage("");
        }
        return true;
    }
    var jumpUrl = getCookie("jumpUrl");
    window.location.href = baseloaction + jumpUrl;
}